<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">

  <!-- PACE Progress Bar START -->
  
    <script src="https://raw.githubusercontent.com/HubSpot/pace/v1.0.2/pace.min.js"></script>
    <link rel="stylesheet" href="https://github.com/HubSpot/pace/raw/master/themes/orange/pace-theme-flash.css">
  
  

  <!-- PACE Progress Bar START -->

  
  <title>使用velocity模板作为导出pdf的模板 | FunGa技术札记</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="velocitypdf">
  
  
  
  
  <meta name="description" content="工作中经常需要导出PDF，如果在Java代码中生成HTML代码，需要进行各种字符串拼接，相当的蛋疼，后来发现Velocity可以很好的起到模板的作用。使用Velocity作为模板写好HTML，我们只需要传我们的对数对象到模板即可渲染我们预期的HTML，然后将该内容生成PDF，简单便捷，更重要的是没了讨厌的HTML字符串拼接的过程。">
<meta name="keywords" content="velocity,pdf">
<meta property="og:type" content="article">
<meta property="og:title" content="使用Velocity模板作为导出PDF的模板">
<meta property="og:url" content="funga.cn/2018/01/20/velocity-pdf/index.html">
<meta property="og:site_name" content="FunGa技术札记">
<meta property="og:description" content="工作中经常需要导出PDF，如果在Java代码中生成HTML代码，需要进行各种字符串拼接，相当的蛋疼，后来发现Velocity可以很好的起到模板的作用。使用Velocity作为模板写好HTML，我们只需要传我们的对数对象到模板即可渲染我们预期的HTML，然后将该内容生成PDF，简单便捷，更重要的是没了讨厌的HTML字符串拼接的过程。">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2018-12-30T04:52:29.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用Velocity模板作为导出PDF的模板">
<meta name="twitter:description" content="工作中经常需要导出PDF，如果在Java代码中生成HTML代码，需要进行各种字符串拼接，相当的蛋疼，后来发现Velocity可以很好的起到模板的作用。使用Velocity作为模板写好HTML，我们只需要传我们的对数对象到模板即可渲染我们预期的HTML，然后将该内容生成PDF，简单便捷，更重要的是没了讨厌的HTML字符串拼接的过程。">
  
    <link rel="alternate" href="/atom.xml" title="FunGa技术札记" type="application/atom+xml">
  
  <link rel="icon" href="/css/images/favicon.ico">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="https://cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");font-weight:400;font-style:italic;}</style>
    
  <link rel="stylesheet" id="athemes-headings-fonts-css" href="//fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A200%2C300%2C400%2C700&amp;ver=4.6.1" type="text/css" media="all">
  <link rel="stylesheet" href="/css/style.css">

  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="/css/hiero.css">
  <link rel="stylesheet" href="/css/glyphs.css">
  
    <link rel="stylesheet" href="/css/vdonate.css">
  

  <!-- Custom CSS -->
  <link rel="stylesheet" href="/css/my.css">
  <!-- Google Adsense -->
  
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>
</html>
<script>
var themeMenus = {};

  themeMenus["/"] = "Home"; 

  themeMenus["/archives"] = "Archives"; 

  themeMenus["/categories"] = "Categories"; 

  themeMenus["/tags"] = "Tags"; 

  themeMenus["/about"] = "About"; 

</script>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  <header id="allheader" class="site-header" role="banner">
  <div class="clearfix container">
      <div class="site-branding">

          <h1 class="site-title">
            
              <a href="/" title="FunGa技术札记" rel="home"> FunGa技术札记 </a>
            
          </h1>

          
            
          <nav id="main-navigation" class="main-navigation" role="navigation">
            <a class="nav-open">Menu</a>
            <a class="nav-close">Close</a>
            <div class="clearfix sf-menu">

              <ul id="main-nav" class="nmenu sf-js-enabled">
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/">Home</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/archives">Archives</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/categories">Categories</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/tags">Tags</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/about">About</a> </li>
                    
              </ul>
            </div>
          </nav>


      </div>
  </div>
</header>




  <div id="container">
    <div id="wrap">
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-velocity-pdf" style="width: 66%; float:left;" class="article article-type-post" itemscope="" itemprop="blogPost">
  <div id="articleInner" class="clearfix post-1016 post type-post status-publish format-standard has-post-thumbnail hentry category-template-2 category-uncategorized tag-codex tag-edge-case tag-featured-image tag-image tag-template">
    
    
      <header class="article-header">
        
  
    <h1 class="thumb" itemprop="name">
      使用Velocity模板作为导出PDF的模板
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	Posted on <a href="/2018/01/20/velocity-pdf/" class="article-date">
	  <time datetime="2018-01-20T09:43:54.000Z" itemprop="datePublished">January 20, 2018</time>
	</a>

      
	<span id="busuanzi_container_page_pv">
	  本文总阅读量<span id="busuanzi_value_page_pv"></span>次
	</span>

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <p>工作中经常需要导出PDF，如果在Java代码中生成HTML代码，需要进行各种字符串拼接，相当的蛋疼，后来发现Velocity可以很好的起到模板的作用。使用Velocity作为模板写好HTML，我们只需要传我们的对数对象到模板即可渲染我们预期的HTML，然后将该内容生成PDF，简单便捷，更重要的是没了讨厌的HTML字符串拼接的过程。<br><a id="more"></a></p>
<h2 id="1、写好Velocity模板"><a href="#1、写好Velocity模板" class="headerlink" title="1、写好Velocity模板"></a>1、写好Velocity模板</h2><p>我们新建一个模板文件，比如xx.vm,里面就是HTML内容，使用Velocity语法直接使用传入的对象数据。</p>
<pre class=" language-html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>html</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>head</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>meta</span> <span class="token attr-name">htp-equiv</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>Content-Type<span class="token punctuation">"</span></span> <span class="token attr-name">content</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>text/html;charset<span class="token punctuation">=</span>UTF-8<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>head</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>style</span><span class="token punctuation">></span></span><span class="token style language-css">
    <span class="token selector"><span class="token class">.positive</span></span><span class="token punctuation">{</span>
        <span class="token property">color</span><span class="token punctuation">:</span> green<span class="token punctuation">;</span>
        <span class="token property">font-size</span><span class="token punctuation">:</span> <span class="token number">32</span>px<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token selector"><span class="token class">.negative</span></span><span class="token punctuation">{</span>
        <span class="token property">color</span><span class="token punctuation">:</span> grey<span class="token punctuation">;</span>
        <span class="token property">font-size</span><span class="token punctuation">:</span> <span class="token number">20</span>px<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>style</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span><span class="token punctuation">></span></span>
        你好,${user.name},
        #if(${user.age} > 18)
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>positive<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>恭喜你,你已经成年了~<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>
        #else
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>negative<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>小朋友,你慢慢喊你回家吃饭了~<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>
        #end
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>html</span><span class="token punctuation">></span></span>
</code></pre>
<h2 id="2-、解析模板帮助类"><a href="#2-、解析模板帮助类" class="headerlink" title="2 、解析模板帮助类"></a>2 、解析模板帮助类</h2><p>该类将我们的对象数据注入到模板中，模板会解析，然后我们返回渲染后的HTML文本内容。</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">VelocityHelper</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> String <span class="token function">getVelocity</span><span class="token punctuation">(</span>String pdfTempName<span class="token punctuation">,</span>Map<span class="token operator">&lt;</span>String<span class="token punctuation">,</span>Object<span class="token operator">></span> data<span class="token punctuation">,</span>HttpServletRequest request<span class="token punctuation">)</span><span class="token punctuation">{</span>

       <span class="token keyword">try</span> <span class="token punctuation">{</span>
           VelocityEngine ve <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">VelocityEngine</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
           Properties properties <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Properties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
           properties<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"file.resource.loader.class"</span><span class="token punctuation">,</span><span class="token string">"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
           ve<span class="token punctuation">.</span><span class="token function">init</span><span class="token punctuation">(</span>properties<span class="token punctuation">)</span><span class="token punctuation">;</span>
           Template template <span class="token operator">=</span> ve<span class="token punctuation">.</span><span class="token function">getTemplate</span><span class="token punctuation">(</span>pdfTempName<span class="token punctuation">,</span><span class="token string">"UTF-8"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
           VelocityContext context <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">VelocityContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
           Set<span class="token operator">&lt;</span>String<span class="token operator">></span> keySet <span class="token operator">=</span> data<span class="token punctuation">.</span><span class="token function">keySet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
           <span class="token keyword">for</span><span class="token punctuation">(</span>String key <span class="token operator">:</span> keySet<span class="token punctuation">)</span><span class="token punctuation">{</span>
               context<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span>data<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
           <span class="token punctuation">}</span>
           StringWriter writer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringWriter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
           template<span class="token punctuation">.</span><span class="token function">merge</span><span class="token punctuation">(</span>context<span class="token punctuation">,</span>writer<span class="token punctuation">)</span><span class="token punctuation">;</span>
           <span class="token keyword">return</span> writer<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
       <span class="token punctuation">}</span><span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span><span class="token punctuation">{</span>
           <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ServiceException</span><span class="token punctuation">(</span><span class="token string">"获取模板错误,信息:"</span><span class="token operator">+</span>e<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
       <span class="token punctuation">}</span>

    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="3、提供PDF的下载"><a href="#3、提供PDF的下载" class="headerlink" title="3、提供PDF的下载"></a>3、提供PDF的下载</h4><pre class=" language-java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">exportPDF</span><span class="token punctuation">(</span>HttpServletRequest request<span class="token punctuation">,</span> HttpServletResponse response<span class="token punctuation">,</span> <span class="token annotation punctuation">@RequestParam</span> <span class="token keyword">int</span> demandId<span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>

            User user <span class="token operator">=</span> <span class="token function">getCurrentUser</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            String fileName <span class="token operator">=</span> user<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">"-"</span> <span class="token operator">+</span> DateUtils<span class="token punctuation">.</span><span class="token function">getDateString</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            Document document <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Document</span><span class="token punctuation">(</span>PageSize<span class="token punctuation">.</span>A4<span class="token punctuation">.</span><span class="token function">rotate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            ByteArrayOutputStream os <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ByteArrayOutputStream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            PdfWriter writer <span class="token operator">=</span> PdfWriter<span class="token punctuation">.</span><span class="token function">getInstance</span><span class="token punctuation">(</span>document<span class="token punctuation">,</span> os<span class="token punctuation">)</span><span class="token punctuation">;</span>
            document<span class="token punctuation">.</span><span class="token function">open</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            document<span class="token punctuation">.</span><span class="token function">addTitle</span><span class="token punctuation">(</span>fileName<span class="token punctuation">)</span><span class="token punctuation">;</span>
            document<span class="token punctuation">.</span><span class="token function">addSubject</span><span class="token punctuation">(</span><span class="token string">"你好"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            document<span class="token punctuation">.</span><span class="token function">addCreationDate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            Map<span class="token operator">&lt;</span>String<span class="token punctuation">,</span> Object<span class="token operator">></span> data <span class="token operator">=</span> Maps<span class="token punctuation">.</span><span class="token function">newHashMap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            data<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"user"</span><span class="token punctuation">,</span> user<span class="token punctuation">)</span><span class="token punctuation">;</span>
            String content <span class="token operator">=</span> VelocityHelper<span class="token punctuation">.</span><span class="token function">getVelocity</span><span class="token punctuation">(</span><span class="token string">"xx.vm"</span><span class="token punctuation">,</span> data<span class="token punctuation">,</span>request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            InputStream htmlStream <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ByteArrayInputStream</span><span class="token punctuation">(</span>content<span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            XMLWorkerHelper<span class="token punctuation">.</span><span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">parseXHtml</span><span class="token punctuation">(</span>writer<span class="token punctuation">,</span> document<span class="token punctuation">,</span> htmlStream<span class="token punctuation">,</span> XMLWorkerHelper<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getResourceAsStream</span><span class="token punctuation">(</span><span class="token string">"/default.css"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">XMLWorkerFontProvider</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token annotation punctuation">@Override</span>
                <span class="token keyword">public</span> Font <span class="token function">getFont</span><span class="token punctuation">(</span><span class="token keyword">final</span> String fontname<span class="token punctuation">,</span> <span class="token keyword">final</span> String encoding<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> embedded<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token keyword">float</span> size<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token keyword">int</span> style<span class="token punctuation">,</span> <span class="token keyword">final</span> BaseColor color<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    BaseFont bf <span class="token operator">=</span> null<span class="token punctuation">;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">{</span>
                        bf <span class="token operator">=</span> BaseFont<span class="token punctuation">.</span><span class="token function">createFont</span><span class="token punctuation">(</span><span class="token string">"STSong-Light"</span><span class="token punctuation">,</span> <span class="token string">"UniGB-UCS2-H"</span><span class="token punctuation">,</span> BaseFont<span class="token punctuation">.</span>NOT_EMBEDDED<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">DocumentException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>
                    Font font <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Font</span><span class="token punctuation">(</span>bf<span class="token punctuation">,</span> size<span class="token punctuation">,</span> style<span class="token punctuation">,</span> color<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    font<span class="token punctuation">.</span><span class="token function">setColor</span><span class="token punctuation">(</span>color<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">return</span> font<span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            document<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            response<span class="token punctuation">.</span><span class="token function">setHeader</span><span class="token punctuation">(</span><span class="token string">"Content-Disposition"</span><span class="token punctuation">,</span> <span class="token string">"attachment; filename="</span> <span class="token operator">+</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span><span class="token punctuation">(</span>fileName <span class="token operator">+</span> <span class="token string">".pdf"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token string">"UTF-8"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">"iso-8859-1"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            response<span class="token punctuation">.</span><span class="token function">setContentType</span><span class="token punctuation">(</span><span class="token string">"application/pdf"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            response<span class="token punctuation">.</span><span class="token function">setContentLength</span><span class="token punctuation">(</span>os<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            OutputStream out <span class="token operator">=</span> response<span class="token punctuation">.</span><span class="token function">getOutputStream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            os<span class="token punctuation">.</span><span class="token function">writeTo</span><span class="token punctuation">(</span>out<span class="token punctuation">)</span><span class="token punctuation">;</span>
            out<span class="token punctuation">.</span><span class="token function">flush</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">DocumentException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
</code></pre>
<p>使用Velocity我们可以处理除了简单的文本，也可以处理非常复杂的对象，比如循环展示列表，根据条件判断展示，等等。</p>

      
    </div>
    <footer class="entry-meta entry-footer">
      
	<span class="ico-folder"></span>
    <a class="article-category-link" href="/categories/开发小招/">开发小招</a>

      
  <span class="ico-tags"></span>
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/pdf/">pdf</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/velocity/">velocity</a></li></ul>

      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!', // 可选参数，打赏标题
  btnText: 'Donate', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: 'https://funga.oss-cn-beijing.aliyuncs.com/config/wechat_pay_code.jpg',
  alipayImage: 'https://funga.oss-cn-beijing.aliyuncs.com/config/alipay_code.png'
});
</script>
      
            
      
        <!--PC版-->
<div id="SOHUCS"></div>
<!-- <script charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/changyan.js" ></script> -->
<script charset="utf-8" type="text/javascript" src="https://funga.oss-cn-beijing.aliyuncs.com/static/changyan.js"></script>
<script type="text/javascript">
window.changyan.api.config({
appid: 'cyrV0wIGI',
conf: 'prod_3d29a99dcddb3782e98f1fa951b9868f'
});
</script>
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2018/02/12/reflex-exc/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          捕获反射执行方法抛出的异常
        
      </div>
    </a>
  
  
    <a href="/2017/12/25/sb-Thymeleaf/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">SpringBoot集成Thymeleaf</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="sidebar">
    <div id="toc" class="toc-article" style="overflow-y: scroll; max-width: 28%;">
    <strong class="toc-title">Contents</strong>
    
      <ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1、写好Velocity模板"><span class="nav-number">1.</span> <span class="nav-text">1、写好Velocity模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-、解析模板帮助类"><span class="nav-number">2.</span> <span class="nav-text">2 、解析模板帮助类</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3、提供PDF的下载"><span class="nav-number">2.0.1.</span> <span class="nav-text">3、提供PDF的下载</span></a></li></ol></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      <footer id="footer" class="site-footer">
  

  <div class="clearfix container">
      <div class="site-info">
	      &copy; 2019 FunGa技术札记 All Rights Reserved.
          
            <span id="busuanzi_container_site_uv">
              本站访客数<span id="busuanzi_value_site_uv"></span>人次  
              本站总访问量<span id="busuanzi_value_site_pv"></span>次
            </span>
          
      </div>
      <div class="site-credit">
        Theme by <a href="https://github.com/iTimeTraveler/hexo-theme-hiero" target="_blank">hiero</a>
      </div>
  </div>
</footer>


<!-- min height -->

<script>
    var contentdiv = document.getElementById("content");

    contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("allheader").offsetHeight - document.getElementById("footer").offsetHeight + "px";
</script>

<!-- Custome JS -->
<script src="/js/my.js"></script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>



  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>


<script src="/js/scripts.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="/js/main.js"></script>







  <div style="display: none;">
    <script src="https://s95.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>
  </div>



	<script async src="https://dnqof95d40fo6.cloudfront.net/atw7f8.js">
	</script>






  </div>

  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js" async=""></script>
</body>
</html>
